﻿using DTcms.Common;
using DTcms.Model;
using DTcms.Web.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web.Mvc;

namespace DTcms.Web.Mvc.Areas.Admin.Controllers
{
    public class OrderController : ManageController
    {
        protected BaseApi _service = new BaseApi();
        protected int totalCount = 0;
        protected Model.manager managerModel = new Model.manager();
        protected string _action;
        protected int _id;
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            managerModel = GetAdminInfo();
            _action = DTRequest.GetQueryString("action");
            _id = DTRequest.GetQueryInt("id");
            ViewBag.action = _action;
            ViewBag.id = _id;
        }
        #region 支付方式
        [ChkAdminScript("order_payment", DTEnums.ActionEnum.View)]
        public ActionResult Payment_List()
        {
            return View();
        }

        [ChkAdminScript("order_payment", DTEnums.ActionEnum.View)]
        public ActionResult site_payment_list()
        {
            return View();
        }
        #region 组合SQL查询语句==========================
        protected string SitePaymentCombSqlTxt(string _keywords, int _site_id)
        {
            StringBuilder strTemp = new StringBuilder();
            if (_site_id > 0)
            {
                strTemp.Append(" and site_id=" + _site_id);
            }
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and title like  '%" + _keywords + "%'");
            }
            return strTemp.ToString();
        }
        #endregion
        #region 数据绑定
        [ChkAdminJson("order_payment", DTEnums.ActionEnum.View)]
        public JsonResult SitePaymentList(string keywords, int site_id = 0, int page = 1, int limit = 10)
        {
            string strWhere = "id > 0" + SitePaymentCombSqlTxt(keywords, site_id);
            string strOrder = "sort_id asc,id desc";
            DataTable resultList = _service.SitePaymentBind(strWhere, strOrder, out totalCount, page, limit);
            DataTable oldData = resultList.Clone();
            if (totalCount > 0)
            {
                oldData.Columns.Add("siteTitle", Type.GetType("System.String"));
                foreach (DataRow item in resultList.Rows)
                {
                    DataRow row = oldData.NewRow();
                    row["title"] = item["title"].ToString(); ;
                    row["ptitle"] = item["ptitle"].ToString(); ;
                    row["add_time"] = item["add_time"];
                    row["is_lock"] = item["is_lock"];
                    row["sort_id"] = item["sort_id"];
                    row["id"] = item["id"];
                    row["siteTitle"] = new BLL.sites().GetTitle(Utils.ObjToInt(item["site_id"]));
                    oldData.Rows.Add(row);
                }
            }
            return Json(new { status = 1, msg = "", item = oldData, totalCount = totalCount });
        }
        #endregion

        #region 组合SQL查询语句==========================
        protected string PaymentCombSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and title like  '%" + _keywords + "%'");
            }
            return strTemp.ToString();
        }
        #endregion
        #region 数据绑定
        [ChkAdminJson("order_payment", DTEnums.ActionEnum.View)]
        public JsonResult PaymentList(string keywords, int page = 1, int limit = 10)
        {
            string strWhere = "id > 0" + PaymentCombSqlTxt(keywords);
            string strOrder = "sort_id asc,id desc";
            List<Model.payment> resultList = _service.PaymentBind(strWhere, strOrder);
            return Json(new { status = 1, msg = "", item = resultList });
        }
        #endregion

        #region 编辑、添加
        [ChkAdminScript("order_payment", DTEnums.ActionEnum.View)]
        public ActionResult Payment_Edit()
        {
            Model.payment model = new Model.payment();
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                _action = DTEnums.ActionEnum.Edit.ToString();//修改类型
                if (_id == 0)
                {
                    return ResultMsg("传输参数不正确！", "back");
                }
                model = _service.OrderPaymentinfo(_id);
                if (model == null)
                {
                    return ResultMsg("记录不存在或已被删除！", "back");
                }
            }
            return View(model);
        }

        [ChkAdminScript("order_payment", DTEnums.ActionEnum.View)]
        public ActionResult site_payment_edit()
        {
            Model.site_payment model = new Model.site_payment();
            int site_id = DTRequest.GetQueryInt("site_id");
            int payment_id = DTRequest.GetQueryInt("payment_id");
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                _action = DTEnums.ActionEnum.Edit.ToString();//修改类型
                if (_id == 0)
                {
                    return ResultMsg("传输参数不正确！", "back");
                }
                model = _service.SiteOrderPaymentinfo(_id);
                if (model == null)
                {
                    return ResultMsg("记录不存在或已被删除！", "back");
                }
                PaymentBind(model.site_id, model.payment_id);
            }
            #region
            if (site_id == model.site_id && model != null)
            {
                PaymentBind(site_id, model.payment_id);
            }
            else if (site_id != 0)
            {
                PaymentBind(site_id, 0);
            }
            if (payment_id > 0)
            {
                ShowFields(payment_id);
            }
            else
            {
                ShowFields(model.payment_id);
            }
            if (site_id != 0)
            {
                model.site_id = site_id;
            }
            if (payment_id != 0)
            {
                model.payment_id = payment_id;
            }
            #endregion

            List<SelectListItem> siteList = new List<SelectListItem>();
            siteList.Add(new SelectListItem() { Text = "请选择站点...", Value = "" });
            siteList.AddRange(_service.SiteTreeBind("is_lock=0", "sort_id asc,id desc"));
            ViewBag.siteList = siteList;

            return View(model);
        }
        #region 显示相关字段=============================
        public void ShowFields(int _payment_id)
        {
            ViewBag.key1 = false;
            ViewBag.key2 = false;
            ViewBag.key3 = false;
            ViewBag.key4 = false;
            Model.payment payModel = new BLL.payment().GetModel(_payment_id);
            if (payModel == null)
            {
                return;
            }
            switch (payModel.api_path.ToLower())
            {
                case "alipaypc":
                    ViewBag.key1 = true;
                    ViewBag.key2 = true;
                    ViewBag.key3 = true;
                    ViewBag.key1_title = "支付宝账号";
                    ViewBag.key1_tip = "*签约支付宝账号或卖家支付宝帐户";
                    ViewBag.key2_title = "合作者身份(partner ID)";
                    ViewBag.key2_tip = "*合作身份者ID，以2088开头由16位纯数字组成的字符串";
                    ViewBag.key3_title = "交易安全校验码(key)";
                    ViewBag.key3_tip = "*交易安全检验码，由数字和字母组成的32位字符串";
                    break;
                case "alipaymb":
                    goto case "alipaypc";
                case "tenpaypc":
                    ViewBag.key1 = true;
                    ViewBag.key2 = true;
                    ViewBag.key1_title = "财付通商户号";
                    ViewBag.key1_tip = "*财付通商家服务商户号";
                    ViewBag.key2_title = "财付通密钥";
                    ViewBag.key2_tip = "*财付通商家服务密钥";
                    break;
                case "chinabankpc":
                    ViewBag.key1 = true;
                    ViewBag.key2 = true;
                    ViewBag.key1_title = "商户编号";
                    ViewBag.key1_tip = "*网银在线商户编号";
                    ViewBag.key2_title = "MD5校验码";
                    ViewBag.key2_tip = "*网银在线MD5校验码";
                    break;
                case "wxapipay":
                    ViewBag.key1 = true;
                    ViewBag.key2 = true;
                    ViewBag.key3 = true;
                    ViewBag.key4 = true;
                    ViewBag.key1_title = "商户号";
                    ViewBag.key1_tip = "*微信支付的商户号";
                    ViewBag.key2_title = "支付密钥";
                    ViewBag.key2_tip = "*商户支付密钥，进入微信支付【账户设置】【API安全】设置";
                    ViewBag.key3_title = "AppID";
                    ViewBag.key3_tip = "*微信公众号的AppID(应用ID)";
                    ViewBag.key4_title = "AppSecret";
                    ViewBag.key4_tip = "*微信公众号的AppSecret(应用密钥)";
                    break;
                case "wxnatpay":
                    ViewBag.key1 = true;
                    ViewBag.key2 = true;
                    ViewBag.key3 = true;
                    ViewBag.key1_title = "商户号";
                    ViewBag.key1_tip = "*微信支付的商户号";
                    ViewBag.key2_title = "支付密钥";
                    ViewBag.key2_tip = "*商户支付密钥，进入微信支付【账户设置】【API安全】设置";
                    ViewBag.key3_title = "AppID";
                    ViewBag.key3_tip = "*微信公众号的AppID(应用ID)";
                    break;
                case "xdd":
                    ViewBag.key1 = true;
                    ViewBag.key2 = true;
                    ViewBag.key3 = true;
                    ViewBag.key1_title = "AppID";
                    ViewBag.key1_tip = "*小叮当支付的AppID(应用ID)";
                    ViewBag.key2_title = "接口密钥";
                    ViewBag.key2_tip = "*商户支付密钥，进入支付【API接口】【详细】设置";
                    ViewBag.key3_title = "支付方式";
                    ViewBag.key3_tip = "*43：支付宝支付  44：微信支付";
                    break;
                case "wxh5pay":
                    goto case "wxnatpay";
                case "f2f":
                    ViewBag.key1 = true;
                    ViewBag.key2 = true;
                    ViewBag.key3 = true;
                    ViewBag.key4 = true;
                    ViewBag.key5 = true;
                    ViewBag.key1_title = "支付宝公钥";
                    ViewBag.key1_tip = "*查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥";
                    ViewBag.key2_title = "开发者私钥";
                    ViewBag.key2_tip = "*使用支付宝开放平台开发助手生成的应用私钥";
                    ViewBag.key3_title = "开发者公钥";
                    ViewBag.key3_tip = "*使用支付宝开放平台开发助手生成的应用公钥";
                    ViewBag.key4_title = "应用ID";
                    ViewBag.key4_tip = "*您的APPID，收款账号既是您的APPID对应支付宝账号";
                    ViewBag.key5_title = "合作伙伴ID";
                    ViewBag.key5_tip = "*合作身份者ID，以2088开头由16位纯数字组成的字符串";
                    break;
                default:
                    ViewBag.key1_title = string.Empty;
                    ViewBag.key2_title = string.Empty;
                    ViewBag.key3_title = string.Empty;
                    ViewBag.key4_title = string.Empty;
                    break;
            }
        }
        #endregion

        #region 绑定平台=================================
        private void PaymentBind(int _site_id, int _payment_id)
        {
            List<SelectListItem> paymentList = new List<SelectListItem>();
            if (_site_id > 0)
            {
                DataTable dt = _service.PaymentBind(_site_id, _payment_id);
                paymentList.Add(new SelectListItem() { Text = "请选择平台...", Value = "" });
                foreach (DataRow dr in dt.Rows)
                {
                    paymentList.Add(new SelectListItem() { Text = dr["title"].ToString(), Value = dr["id"].ToString() });
                }
            }
            else
            {
                paymentList.Add(new SelectListItem() { Text = "请选择站点...", Value = "" });
            }
            ViewBag.paymentList = paymentList;
        }
        #endregion
        [HttpPost,ValidateInput(false), CustomValidateAntiForgeryToken]
        public ActionResult PaymentSave(Model.payment t)
        {
            SaveModel save = _service.OrderPaymentSave(_action, _id, t);
            save.url = save.status == 0 ? "back" : "../order/payment_list";
            return Json(save);
        }

        [HttpPost, ValidateInput(false),CustomValidateAntiForgeryToken]
        public ActionResult SItePaymentSave(Model.site_payment t)
        {
            SaveModel save = _service.SiteOrderPaymentSave(_action, _id, t);
            save.url = save.status == 0 ? "back" : "../order/site_payment_list";
            return Json(save);
        }
        #endregion

        [HttpPost]
        [ChkAdminJson("order_payment", DTEnums.ActionEnum.Edit)]
        public JsonResult PaymentLock(int id, bool is_lock)
        {
            BLL.payment bll = new BLL.payment();
            if (bll.UpdateFile("id=" + id, "is_lock=" + (is_lock ? 0 : 1)))
            {
                return Json(new { status = 1, msg = "状态修改成功！" });
            }
            return Json(new { status = 0, msg = "状态修改失败！" });
        }

        [HttpPost]
        [ChkAdminJson("order_payment", DTEnums.ActionEnum.Edit)]
        public JsonResult SitePaymentLock(int id, bool is_lock)
        {
            BLL.site_payment bll = new BLL.site_payment();
            if (bll.UpdateFile("id=" + id, "is_lock=" + (is_lock ? 0 : 1)))
            {
                return Json(new { status = 1, msg = "状态修改成功！" });
            }
            return Json(new { status = 0, msg = "状态修改失败！" });
        }

        [HttpPost]
        [ChkAdminJson("order_payment", DTEnums.ActionEnum.Edit)]
        public JsonResult PaymentFiledSave(string field, int value, int id = 0)
        {
            if (string.IsNullOrEmpty(field) || id == 0)
            {
                return Json(new { status = 0, msg = "参数错误！" });
            }
            BLL.payment bll = new BLL.payment();
            if (bll.UpdateFile("id=" + id, field + "=" + value))
            {
                return Json(new { status = 1, msg = "修改成功！" });
            }
            return Json(new { status = 0, msg = "修改失败！" });
        }

        [HttpPost]
        [ChkAdminJson("order_payment", DTEnums.ActionEnum.Edit)]
        public JsonResult SitePaymentFiledSave(string field, int value, int id = 0)
        {
            if (string.IsNullOrEmpty(field) || id == 0)
            {
                return Json(new { status = 0, msg = "参数错误！" });
            }
            BLL.site_payment bll = new BLL.site_payment();
            if (bll.UpdateFile("id=" + id, field + "=" + value))
            {
                return Json(new { status = 1, msg = "修改成功！" });
            }
            return Json(new { status = 0, msg = "修改失败！" });
        }
        #endregion

        #region 订单管理
        [ChkAdminScript("order_list", DTEnums.ActionEnum.View)]
        public ActionResult Order_List()
        {
            return View();
        }
        
        [ChkAdminScript("order_confirm", DTEnums.ActionEnum.View)]
        public ActionResult Order_Confirm()
        {
            return View();
        }

        [ChkAdminScript("order_config", DTEnums.ActionEnum.View)]
        public ActionResult Order_Config()
        {
            return View(_service.OrderConfigInfo());
        }
        #region 保存
        [HttpPost, ValidateInput(false)]
        [ChkAdminJson("order_config", DTEnums.ActionEnum.Edit)]
        public ActionResult ConfigSave(Model.orderconfig t)
        {
            SaveModel save = _service.OrderConfigSave(t);
            save.url = save.status == 0 ? "back" : "../order/order_config";
            return Json(save);
        }
        
        #region 删除
        [HttpPost]
        [ChkAdminJson("order_payment", DTEnums.ActionEnum.Delete)]
        public JsonResult SitePaymentDelete(List<int> ids)
        {
            return _service.SitePaymentDelete(ids);
        }
        #endregion
        #endregion
        #endregion

        #region 物流配送
        [ChkAdminScript("order_express", DTEnums.ActionEnum.View)]
        public ActionResult Express_List()
        {
            return View();
        }

        #region 组合SQL查询语句==========================
        protected string ExpressCombSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and (title like  '%" + _keywords + "%' or express_code like '%" + _keywords + "%')");
            }
            return strTemp.ToString();
        }
        #endregion
        #region 数据绑定
        [ChkAdminJson("order_express", DTEnums.ActionEnum.View)]
        public JsonResult ExpressList(string keywords, int page = 1, int limit = 10)
        {
            string strWhere = "id > 0" + ExpressCombSqlTxt(keywords);
            string strOrder = "sort_id asc,id desc";
            var resultList = _service.OrderExpressBind(strWhere, strOrder, page, limit);
            return Json(new { status = 1, msg = "", item = resultList.Items, totalCount = resultList.TotalItems });
        }
        #endregion

        #region 删除
        [HttpPost]
        [ChkAdminJson("order_express", DTEnums.ActionEnum.Delete)]
        public JsonResult ExpressDelete(List<int> ids)
        {
            return _service.OrderExpressDelete(ids);
        }
        #endregion

        [HttpPost]
        [ChkAdminJson("order_express", DTEnums.ActionEnum.Edit)]
        public JsonResult ExpressLock(int id, bool is_lock)
        {
            BLL.express bll = new BLL.express();
            if (bll.UpdateFile("id=" + id, "is_lock=" + (is_lock ? 0 : 1)))
            {
                return Json(new { status = 1, msg = "状态修改成功！" });
            }
            return Json(new { status = 0, msg = "状态修改失败！" });
        }

        [HttpPost]
        [ChkAdminJson("order_express", DTEnums.ActionEnum.Edit)]
        public JsonResult ExpressFieldSave(string field, string value, int id = 0)
        {
            if (string.IsNullOrEmpty(field) || id == 0)
            {
                return Json(new { status = 0, msg = "参数错误！" });
            }
            BLL.express bll = new BLL.express();
            if (bll.UpdateFile("id=" + id, field + "=" + value))
            {
                return Json(new { status = 1, msg = "修改成功！" });
            }
            return Json(new { status = 0, msg = "修改失败！" });
        }

        [ChkAdminScript("order_express", DTEnums.ActionEnum.View)]
        public ActionResult Express_Edit()
        {
            Model.express model = new Model.express();
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                _action = DTEnums.ActionEnum.Edit.ToString();//修改类型
                if (_id == 0)
                {
                    return ResultMsg("传输参数不正确！", "back");
                }
                model = _service.OrderExpressInfo(_id);
                if (model == null)
                {
                    return ResultMsg("记录不存在或已被删除！", "back");
                }
            }
            return View(model);
        }

        [HttpPost,CustomValidateAntiForgeryToken]
        public ActionResult ExpressSave(Model.express t)
        {
            SaveModel save = _service.OrderExpressSave(_action, _id, t);
            save.url = save.status == 0 ? "back" : "../order/express_list";
            return Json(save);
        }
        #endregion
    }
}
